package com.jeesite.modules.dataScreen.service;

import com.alibaba.fastjson2.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeesite.modules.dataScreen.dao.EventOrderProcessDao;
import com.jeesite.modules.dataScreen.entity.EventOrderProcess;
import com.jeesite.modules.dataScreen.enums.SourceSystemCodeEnum;
import com.jeesite.modules.dataScreen.web.dto.EventOrderLogDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author machenzhi
 * @date 2024/08/08 10:17
 */
@Service
@Slf4j
@DS("theme-db")
public class EventOrderProcessService extends ServiceImpl<EventOrderProcessDao, EventOrderProcess> {

    @Autowired
    @Lazy
    private EventOrderService eventOrderService;


    @Transactional(rollbackFor = Exception.class)
    public synchronized void add(EventOrderLogDTO dto) {

        String eventNum = dto.getEventNum();
        String sourceSystemCode = dto.getSourceSystemCode();
        SourceSystemCodeEnum anEnum = SourceSystemCodeEnum.getEnum(sourceSystemCode);
        if (Objects.isNull(anEnum)) {
            log.error("应用识别码不存在 dto:{}", JSON.toJSONString(dto));
            throw new IllegalArgumentException("应用识别码不存在");
        }

        Optional.ofNullable(eventOrderService.getByEventNum(eventNum, sourceSystemCode))
                .orElseThrow(() -> {
                    log.error("事件不存在 dto:{}", JSON.toJSONString(dto));
                    return new IllegalArgumentException("事件不存在");
                });

        //删除处置数据
        removeByEventNum(eventNum, sourceSystemCode);
        List<EventOrderProcess> logList = dto.getLogList();

        //插入新处置
        logList.forEach(o -> {
            o.setEventNum(eventNum);
            o.setSourceSystemCode(sourceSystemCode);
        });
        this.saveBatch(logList);

        //如果最新的处置是已结案，刷新事件表的状态
         logList.stream()
                .max(Comparator.comparing(EventOrderProcess::getExecuteTime))
                .ifPresent(o -> {
                    String endStatus = o.getEndStatus();
                    if (Objects.equals(endStatus, "1")) {
                        eventOrderService.modifyEndStatus(eventNum);
                    }
                });
    }


    public void removeByEventNum(String eventNum, String sourceSystemCode) {
        LambdaQueryWrapper<EventOrderProcess> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EventOrderProcess::getEventNum, eventNum)
                .eq(EventOrderProcess::getSourceSystemCode, sourceSystemCode);
        this.remove(queryWrapper);
    }


    public List<EventOrderProcess> list(String eventNum, String sourceSystemCode) {
        LambdaQueryWrapper<EventOrderProcess> processQueryWrapper = new LambdaQueryWrapper<>();
        processQueryWrapper.eq(EventOrderProcess::getEventNum, eventNum).eq(EventOrderProcess::getSourceSystemCode, sourceSystemCode);
        return this.list(processQueryWrapper);
    }
}
